<template>
  <div class="app-list-page">
    <a-tabs v-model:activeKey="activeKey">
    <a-tab-pane :key="1" tab="企业设置">
      <a-card :bordered="false" style="width: 100%; border-radius: 6px">
      <a-form :model="formRef" layout="vertical" style="width: 400px">
        <a-form-item label="团队名称" v-bind="validateInfos.name">
          <a-input v-model:value="formRef.name" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="团队简介" v-bind="validateInfos.intro">
          <a-input v-model:value="formRef.intro" placeholder="一句话介绍" />
        </a-form-item>
        <a-form-item label="团队图标" v-bind="validateInfos.avatar">
          <a-upload
            :action="$utils.imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            v-model:file-list="fileList"
            @change="handleUploadChange"
            :multiple="true"
            name="image"
            :data="{ dir: 'work_ai' }"
            accept="image/*"
            list-type="picture-card"
          >
            <div v-if="!fileList.length">
              <PlusOutlined />
              <div>上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="onSubmit" style="margin-left: 10px"
        >保存</a-button
      >
      
    </a-card>

    </a-tab-pane>
    <a-tab-pane :key="2" tab="企业权益" force-render>
      <a-card :bordered="false" style="width: 100%; border-radius: 6px;background-color: unset;">
        <div class="expiration-time">
            <div class="font-bold">
              <span>AI机器人有效期至：</span>
              <span>{{ detail.deadline }}</span>
            </div>
            <div>
              <a-button type="link" @click="showMemberShip = true">升级/续费版本，享更多权益 ></a-button>
            </div>
        </div>
        <div class="rights-options">
            <div class="right-item">
              <div class="right-item-img">
                <img src="../../common//image/robot.png" class="right-item-img">
              </div>
              <div>
                  <div class="right-item-title">创建机器人个数</div>
                  <div class="right-item-content">
                    <span> {{ detail.app.existNum }}/{{ detail.app.totalNum }}</span>
                    <span class="ml-10 text-grey">已创建数/总数</span>
                  </div>
              </div>
            </div>
            <div class="right-item">
              <div class="right-item-img">
                <img src="../../common//image/team.png" class="right-item-img">
              </div>
              <div>
                  <div class="right-item-title">团队成员数</div>
                  <div class="right-item-content">
                    <span> {{ detail.user.existNum }}/{{ detail.user.totalNum }}</span>
                    <span class="ml-10 text-grey">已添加数/总数</span>
                  </div>
              </div>
            </div>
            <div class="right-item">
              <div class="right-item-img">
                <img src="../../common//image/ai-dialog-icon.png" class="right-item-img">
              </div>
              <div>
                  <div class="right-item-title" @click="userPackageVisible=true">AI对话包，剩余字数<a-button type="link" style="padding:0 5px;height: 0;">明细</a-button></div>
                  <div class="right-item-content">
                    <span> {{ detail.total_word_numbers }}</span>
                    <a-button type="link" class="ml-10" style="padding:0 5px;height: 0;" @click="showMemberShip = true">充值</a-button>
                  </div>
              </div>
            </div>
            <div class="right-item">
              <div class="right-item-img">
                <img src="../../common//image/draw-icon.png" class="right-item-img">
              </div>
              <div>
                  <div class="right-item-title">AI绘画次数</div>
                  <div class="right-item-content">
                    <span> {{ detail.draw.existNum }}/{{ detail.draw.totalNum }}</span>
                    <span class="ml-10 text-grey">已生成/总数</span>
                  </div>
              </div>
            </div>
        </div>
      </a-card>
    </a-tab-pane>
  
  </a-tabs>
   
  <memberShip :visible="showMemberShip" :isTeam="true" @close="closeMemberShip" />
    <a-modal :width="1200" v-model:visible="userPackageVisible" title="查看套餐包" :footer="false">
      <a-table :dataSource="packages" :columns="tableColumns" :pagination="false"></a-table>
    </a-modal>
    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />
  </div>
</template>

<script>
import {
  ref,
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  inject,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Form, Modal, notification, message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { useTeam, useTeamState } from "@/hooks/team";
import memberShip from "../vip/modules/memberShip.vue";
const useForm = Form.useForm;
export default defineComponent({
  name: "Create",
  components: {
    PlusOutlined,
    memberShip,
  },

  setup() {
    const route = useRoute();
    const router = useRouter();
    const changeTeamPopoverVisible = inject(["changeTeamPopoverVisible"]);

    const state = reactive({
      showMemberShip:false,
      packages:[],
      tableColumns:[
      {
        title: '来源',
        dataIndex: 'from_text',
        key: 'from',
        width: 100
      },
      {
        title: '类型',
        dataIndex: 'type_text',
        key: 'type',
        width: 100
      },
      {
        title: '总次数',
        dataIndex: 'total_numbers',
        key: 'total_numbers',
        width: 100
      },
      {
        title: '剩余次数',
        dataIndex: 'left_numbers',
        key: 'left_numbers',
        width: 100
      },
      {
        title: '剩余字数',
        dataIndex: 'left_words_number',
        key: 'left_words_number',
        width: 120
      },
      {
        title: '总允许绘画数',
        dataIndex: 'art_total_numbers',
        key: 'art_total_numbers',
        width: 120
      },
      {
        title: '剩余绘画数',
        dataIndex: 'art_left_numbers',
        key: 'art_left_numbers',
        width: 120
      },
      {
        title: '有效期',
        dataIndex: 'end_date',
        key: 'end_date',
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
        key: 'created_at',
      }
  
      ],
      userPackageVisible:false,
       detail:{
        total_word_numbers:0,
        app:{
          existNum:0,
          totalNum:0,
        },
        user:{
          existNum:0,
          totalNum:0,
        },
        draw:{
          existNum:0,
          totalNum:0,
        }
       },
      activeKey:1,
      loginVisible: false,
      showPage: false,
      fileList: [],
    });

    const formRef = reactive({
      name: "",
      intro: "",
      avatar: "",
      total_numbers: 0,
      total_art_numbers: 0,
      total_word_numbers: 0
    });

    const rulesRef = reactive({
      name: [{ required: true, message: "团队名称不能为空" }],
    });

    const { resetFields, validate, validateInfos } = useForm(formRef, rulesRef);

    const getTeamDetail = () => {
      state.fileList = [];
      resetFields();
      request
        .get("/work_ai", "/user/team", {
          id: store.state.user.teamId,
        })
        .then((res) => {
          if (res.detail) {
            for (let key in formRef) {
              formRef[key] = res.detail[key];
            }
            if (res.detail.avatar) {
              state.fileList.push({
                uid: 1,
                name: res.detail.avatar,
                status: "done",
                url: res.detail.avatar,
              });
            }
          }
        });
    };

    const aiConfig = ref({
      ai_draw_open: false
    })

    const init = () => {
      if (store.state.user.teamId) {
        getTeamDetail();
      }

      store.dispatch("getAiConfig").then((config) => {
        aiConfig.value = config
      })
    };

    utils.checkLogin().then((isLogin) => {
      if (!isLogin) {
        state.loginVisible = true;
        return;
      }
      state.showPage = true;
      init();
    });

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    // 上传图片
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      state.fileList = resFileList;
      if (state.fileList.length) {
        formRef.avatar = state.fileList[0].url;
      } else {
        formRef.avatar = "";
      }
    };

    const onSubmit = () => {
      validate().then(() => {
        let params = {
          id: store.state.user.teamId,
        };
        for (let key in formRef) {
          params[key] = formRef[key];
        }
        request
          .put("/work_ai", "/user/team", {
            ...params,
          })
          .then((res) => {
            message.success("保存成功");
            getTeamDetail();
          });
      });
    };
    // 企业权益
    const getTeamInfo = ()=>{
      let requestType = "post";
      let url = "/user/team/statistics";
      let params = {
        
        team_id: store.state.user.teamId,
      };
      
      request[requestType]("/work_ai", url, {
        ...params,
      }).then((res) => {
          console.log(res,'xxxxxx');
          state.detail = res.result
          state.packages = res?.result?.packages??[]
      });
    }
    getTeamInfo()
    watch(
      () => store.state.user.teamId,
      (val) => {
        init();
      }
    );
    const closeMemberShip = ()=>{
      state.showMemberShip = false;
    }
    return {
      ...toRefs(state),
      loginCallback,
      handleUploadChange,
      validateInfos,
      formRef,
      onSubmit,
      aiConfig,
      closeMemberShip
    };
  },
});
</script>

<style lang="less" scoped>
.app-list-page {
  width: 100%;
  height: 100%;
  padding: 20px;

  .ant-page-header-content {
    padding-top: 0px;
  }

  .app-list-wrap {
    .app-list {
      padding: 20px 0 40px 20px;
      .app-item {
        height: 140px;
        padding: 15px 20px;
        background-color: #fff;
        border-radius: 12px;
        margin-right: 20px;
        margin-bottom: 20px;
        cursor: pointer;
        transition: 0.2s ease;
        box-shadow: 0 0px 10px #193e7b14;
        position: relative;

        &:hover {
          -webkit-transform: translateY(-3px);
          -ms-transform: translateY(-3px);
          transform: translateY(-3px);
          -webkit-transition: all 0.5s ease-out;
          transition: all 0.5s ease-out;
          background-color: #f3f0ff;

          .close-button {
            display: block;
          }
        }

        .app-item-logo {
          width: 48px;
          height: 48px;
          object-fit: cover;
          margin-right: 20px;
        }

        .app-item-name {
          font-size: 20px;
        }

        .app-item-intro {
          margin-top: 10px;
          color: #666;
          font-size: 16px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .close-button {
          position: absolute;
          top: -5px;
          right: -5px;
          font-size: 18px;
          color: #666;
          display: none;
          -webkit-transition: all 0.5s ease-out;
          transition: all 0.5s ease-out;
        }
      }
    }

    .pagination-wrap {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-right: 20px;
    }
  }

  .empty-wrap {
    width: 100%;
    display: flex;
    justify-content: center;
    padding-top: 150px;
  }
}
// 有效期
.expiration-time {
  display: flex;
  width: 100%;
  min-width: 1000px;
  justify-content: space-between;
  align-items: center;
  height: 80px;
  padding: 20px;
  background-image: url('~@/common/image/bg.jpg');
  background-size: cover; /* 让背景图像充满容器，可能会裁剪部分图像 */
  background-position: center; /* 将背景图像居中显示 */
  background-repeat: no-repeat;
  border-radius: 5px;
  border: 1px solid #fff;
}
// 权益选项
.rights-options {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-top: 30px;
}
.right-item{
  flex: 1;
  min-width: 300px;
  display: flex;
  align-items: center;
  background: #fff;
  padding: 20px;
  border-radius: 5px;
  color:#000;
}
.right-item-img{
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: contain;
  margin-right: 10px;
}
.right-item-title{
  margin-bottom: 5px;
}
.text-grey{
  color: #aaa;
}
</style>
